package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.util.MyKafkaUtil;
import com.google.common.collect.Lists;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/17 10:24
 */
public class DWMUVApp extends BaseApp {
    public static void main(String[] args) {
        /*
            app
                启动日志
            网页
                没有启动日志
         */
        new DWMUVApp().init(20001, 2, "DWMUVApp", "DWMUVApp", "dwd_page_log");
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    DataStreamSource<String> sourceStream) {
        sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((ele, recordTimestamp) -> ele.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private SimpleDateFormat simpleDateFormat;
                private ValueState<Long> firstVisitTsState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitTsState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Long>("firstVisitTsState", Long.class));
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                }
                
                @Override
                public void process(String s,
                                    Context context,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 条件1: 用来判断第一天
                    // 条件2: 判断第二天...
                    // 用水印的日志表示今天
                    // Bug: 如果水印到了 0:0:1 到今天, 这个时候会触发昨天的窗口, 不一致: 水印是今天, 窗口是昨天的窗口
                    //
                    /*final String today = simpleDateFormat.format(new Date(context.currentWatermark()));
                    if (firstVisitTsState.value() == null
                        || !today.equals(simpleDateFormat.format(new Date(firstVisitTsState.value())))) {
                        // 使用google的工具, 把Iterable直接转成ArrayList
                        final ArrayList<JSONObject> list = Lists.newArrayList(elements);
                        final JSONObject firstVisit = Collections
                            .min(list, Comparator.comparing(o -> o.getLong("ts")));
                        
                        if (firstVisitTsState.value() == null || simpleDateFormat.format(new Date(firstVisit.getLong("ts"))).equals(today)) {
                            // 水印已经到了今天, 但是窗口还是昨天的窗口
                            // 把第一次的访问记录发送到下游
                            out.collect(firstVisit);
                            firstVisitTsState.update(firstVisit.getLong("ts"));
                        }
                    }*/
                    
                    final String today = simpleDateFormat.format(new Date(context.window().getEnd()));
                    if (firstVisitTsState.value() == null
                        || !today.equals(simpleDateFormat.format(new Date(firstVisitTsState.value())))) {
                        // 使用google的工具, 把Iterable直接转成ArrayList
                        final ArrayList<JSONObject> list = Lists.newArrayList(elements);
                        final JSONObject firstVisit = Collections
                            .min(list, Comparator.comparing(o -> o.getLong("ts")));
                        
                        // 水印已经到了今天, 但是窗口还是昨天的窗口
                        // 把第一次的访问记录发送到下游
                        out.collect(firstVisit);
                        firstVisitTsState.update(firstVisit.getLong("ts"));
                    }
                    
                }
            })
            .map(obj -> JSON.toJSONString(obj))
            .addSink(MyKafkaUtil.getFlinkKafkaSink("dwm_uv"));
    }
}
